#pragma once 
#include<iostream>
#include<string>
#include<strings.h>
#include<cstring>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<unistd.h>
#include<cstdlib>
#include<sys/wait.h>
#include<pthread.h>

enum{
    SOCKET_ERR = 2,
    BIND_ERR,
    LISTEN_ERR

};

const int n = 10;

class Sock
{
public:
    Sock()
    {}

    ~Sock()
    {}

    //创建套接字接口
    void Socket()
    {
        sockfd_ = socket(AF_INET,SOCK_STREAM,0);
        if(sockfd_ < 0)
        {
            std::cout << "创建套接字失败....." << std::endl; 
            exit(SOCKET_ERR);
        }
    }

    //绑定接口
    void Bind(uint16_t port)
    {
        struct sockaddr_in local;
        bzero(&local,sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(port); //转网络字节序
        local.sin_addr.s_addr = INADDR_ANY;

        if(bind(sockfd_,(struct sockaddr*)&local,sizeof(local)) < 0)
        {
            std::cout << "绑定错误...." << std::endl;
            exit(BIND_ERR);
        }
    }

    //监听接口
    void Listen()
    {
        if(listen(sockfd_,n) < 0)
        {
            std::cout << "监听失败...." << std::endl;
            exit(LISTEN_ERR);
        }
    }

    //接收接口
    int Accept(std::string* clientip,uint16_t* clientport)
    {
        struct sockaddr_in peer;
        socklen_t len = sizeof(peer);
        int newfd = accept(sockfd_,(struct sockaddr*)&peer,&len);
        if(newfd < 0)
        {
            std::cout << "接收失败...." << std::endl; 
            return -1;   
        }
        char ipstr[64];
        inet_ntop(AF_INET,&peer.sin_addr,ipstr,sizeof(ipstr));
        *clientip = ipstr;
        *clientport = ntohs(peer.sin_port);

        return newfd;
    }

    //客户端连接服务端
    bool Connect(const std::string& ip, const uint16_t& port) 
    {
        struct sockaddr_in peer;
        bzero(&peer,sizeof(peer));
        peer.sin_family = AF_INET;
        peer.sin_port = htons(port); //转网络字节序
        inet_pton(AF_INET,ip.c_str(),&(peer.sin_addr));

        int n = connect(sockfd_,(struct sockaddr*)&peer,sizeof(peer));
        if(n == -1) //没有连接成功
        {
            std::cout << "连接失败...." << std::endl;
            return false;
        }
        return true;
    }

    void Close()
    {
        close(sockfd_);
    }

private:
    int sockfd_;
};
